# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         testsuite_result.py
# Description:  
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019/11/21 11:13
# -------------------------------------------------------------------------------
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import status
from rest_framework.filters import OrderingFilter
from rest_framework.generics import DestroyAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet

from apps.BasicAuthService.models import Role
from apps.HttpAutoTestService.filters import TestsuiteResultFilter
from apps.HttpAutoTestService.models import TestsuiteResult, TestcaseResult
from apps.HttpAutoTestService.serializers import TestsuiteResultListSerializer

__all__ = ['TestsuiteResultVersionAPIView', 'TestsuiteResultListViewSet', 'TestsuiteResultBatchDestroyAPIView']


class TestsuiteResultVersionAPIView(APIView):
    """
    测试场景结果最新的10个版本号
    """

    def get(self, request, *args, **kwargs):
        user = self.request.user
        testsuite_results = TestsuiteResult.objects.filter(is_deleted=False)
        if not Role.objects.filter(code='SUPERADMIN', user=user, is_deleted=False):
            testsuite_results = testsuite_results.filter(project__members=self.request.user)
        data = testsuite_results.order_by('-version').values('version').distinct()[:10]
        for item in data:
            res = TestsuiteResult.objects.filter(
                version=item.get('version'), is_deleted=False
            ).values_list('status', flat=True)
            res = list(set(res))
            if len(res) == 1:
                item['status'] = res[0]
            else:
                item['status'] = 'PARTIAL_PASS'
        return Response(status=status.HTTP_200_OK, data=data, content_type='application/json')


class TestsuiteResultListViewSet(ReadOnlyModelViewSet):
    """
    场景结果列表
    """
    serializer_class = TestsuiteResultListSerializer
    filter_backends = (DjangoFilterBackend, OrderingFilter)
    filter_class = TestsuiteResultFilter
    ordering_fields = ['execute_time', 'version']

    def get_queryset(self):
        user = self.request.user
        testsuite_results = TestsuiteResult.objects.filter(is_deleted=False)
        if not Role.objects.filter(code='SUPERADMIN', user=user, is_deleted=False):
            testsuite_results = testsuite_results.filter(project__members=self.request.user)
        return testsuite_results


class TestsuiteResultBatchDestroyAPIView(DestroyAPIView):
    """
    场景结果批量删除
    """

    def delete(self, request, *args, **kwargs):
        data = request.data
        permanent = data.get('permanent')  # true：永久(物理)删除，false：临时(逻辑)删除
        testsuite_result_ids = data.get('testsuiteResults')
        if permanent:
            TestsuiteResult.objects.filter(id__in=testsuite_result_ids).delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        TestsuiteResult.objects.filter(id__in=testsuite_result_ids).update(is_deleted=True)
        TestcaseResult.objects.filter(testsuite_result__id__in=testsuite_result_ids).update(is_deleted=True)
        return Response(status=status.HTTP_200_OK, data='临时删除成功', content_type='application/json')
